<template>
	<view class="login-container" :style="{ paddingTop: safeAreaInsets.top + 'px' }">
		<!-- 顶部装饰 -->
		<view class="top-decoration">
			<view class="decoration-circle circle1"></view>
			<view class="decoration-circle circle2"></view>
			<view class="decoration-circle circle3"></view>
		</view>

		<!-- Logo和标题区域 -->
		<view class="header-section">
			<view class="logo-container">
				<image class="logo" src="/static/images/logo.png" mode="aspectFit"></image>
			</view>
			<text class="app-title">热链传导系统</text>
			<text class="welcome-text">欢迎使用热链传导系统</text>
		</view>

		<!-- 登录卡片 -->
		<view class="login-card">
			<view class="card-header">
				<text class="card-title">微信快捷登录</text>
				<text class="card-subtitle">使用微信手机号一键登录注册</text>
			</view>

			<!-- 登录按钮区域 -->
			<view class="button-section">
				<button class="wx-login-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"
					:loading="loading" :disabled="loading">
					<view class="btn-content">
						<view class="wx-icon" v-if="!loading">🔐</view>
						<text class="btn-text">
							{{ loading ? '登录中...' : '微信手机号登录' }}
						</text>
					</view>
				</button>
			</view>

			<!-- 状态提示 -->
			<view class="status-section" v-if="statusMessage">
				<view class="status-message" :class="statusType">
					<text class="status-icon">{{ statusIcon }}</text>
					<text class="status-text">{{ statusMessage }}</text>
				</view>
			</view>
		</view>

		<!-- 功能说明 -->
		<view class="feature-section">
			<view class="feature-item">
				<text class="feature-icon">🚀</text>
				<text class="feature-text">快速注册登录</text>
			</view>
			<view class="feature-item">
				<text class="feature-icon">🔒</text>
				<text class="feature-text">安全可靠</text>
			</view>
			<view class="feature-item">
				<text class="feature-icon">🔗</text>
				<text class="feature-text">热链传导</text>
			</view>
		</view>

		<!-- 底部协议 -->
		<view class="agreement-section">
			<view class="agreement-wrapper">
				<text class="agreement-text">
					登录即表示同意
					<text class="agreement-link" @click="showUserAgreement">《用户协议》</text>
					和
					<text class="agreement-link" @click="showPrivacyPolicy">《隐私政策》</text>
				</text>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, computed } from 'vue'
	import { getWxPhoneNumber } from '@/api/oauth'
	import modal from '@/plugins/modal'
	import useUserStore from '@/store/modules/user'

	const userStore = useUserStore()

	const loading = ref(false)
	const statusMessage = ref('')
	const statusType = ref('info') // success, error, info

	// 获取屏幕边界到安全区域距离
	const { safeAreaInsets } = uni.getWindowInfo()

	// 计算状态图标
	const statusIcon = computed(() => {
		switch (statusType.value) {
			case 'success': return '✅'
			case 'error': return '❌'
			default: return 'ℹ️'
		}
	})

	// 设置状态信息
	const setStatus = (type : string, message : string) => {
		statusType.value = type
		statusMessage.value = message
	}

	// 登录成功处理
	function loginSuccess() {
		userStore.getInfo().then(res => {
			console.log('用户信息:', res.user)
			if (res.user.loginDate === null) {
				// 新用户，跳转到标签选择页面
				uni.navigateTo({
					url: '/pages/register/newUserSelect'
				})
			} else {
				// 老用户，跳转到首页
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		}).catch(error => {
			console.error('获取用户信息失败:', error)
			setStatus('error', '登录失败，请重试')
		})
	}

	/**
	 * 获取微信手机号回调
	 * @param e 回调事件
	 */
	const getPhoneNumber = async (e : any) => {
		console.log('微信手机号授权回调:', e)

		if (e.detail.errMsg === 'getPhoneNumber:ok') {
			// 用户同意授权
			const code = e.detail.code
			console.log('获取到动态令牌code:', code)

			if (code) {
				loading.value = true
				setStatus('info', '正在登录...')

				try {
					// 调用后端接口获取手机号
					const response = await getWxPhoneNumber(code)

					if (response.code === 200) {
						const phoneNumber = response.phoneNumber
						console.log('获取到手机号:', phoneNumber)

						// 清除之前的登录状态
						userStore.logOut()

						// 执行登录（后端同时完成注册和登录）
						try {
							await userStore.miniAppLogin(phoneNumber)
							setStatus('success', '登录成功！正在跳转...')

							// 延迟跳转，让用户看到成功提示
							setTimeout(() => {
								loginSuccess()
							}, 1000)
						} catch (loginError) {
							console.error('登录失败:', loginError)
							setStatus('error', '登录失败，请重试')
							modal.msgError('登录失败，请重试')
						}
					} else {
						setStatus('error', '获取手机号失败：' + response.msg)
						modal.msgError('获取手机号失败：' + response.msg)
					}
				} catch (error) {
					console.error('获取手机号失败:', error)
					setStatus('error', '网络错误，请检查网络连接')
					modal.msgError('网络错误，请检查网络连接')
				} finally {
					loading.value = false
				}
			} else {
				setStatus('error', '未获取到有效的授权码')
				modal.msgError('未获取到有效的授权码')
			}
		} else if (e.detail.errMsg === 'getPhoneNumber:fail user deny') {
			// 用户拒绝授权
			setStatus('error', '需要手机号授权才能登录')
			modal.msgError('需要手机号授权才能登录')
		} else {
			// 其他错误
			setStatus('error', '授权失败：' + e.detail.errMsg)
			modal.msgError('授权失败，请重试')
			console.log('授权错误码:', e.detail.errno)
		}
	}

	// 显示用户协议
	const showUserAgreement = () => {
		uni.navigateTo({
			url: '/pages/agreement/userAgreement'
		})
	}

	// 显示隐私政策
	const showPrivacyPolicy = () => {
		uni.navigateTo({
			url: '/pages/agreement/privacyPolicy'
		})
	}
</script>

<style lang="scss" scoped>
	.login-container {
		min-height: 100vh;
		background: #f8f9fa;
		position: relative;
		padding: 40rpx;
		display: flex;
		flex-direction: column;
	}

	// 顶部装饰
	.top-decoration {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		height: 300rpx;
		overflow: hidden;
		z-index: 0;

		.decoration-circle {
			position: absolute;
			border-radius: 50%;
			background: rgba(102, 126, 234, 0.08);

			&.circle1 {
				width: 200rpx;
				height: 200rpx;
				top: -100rpx;
				right: -50rpx;
				animation: float 6s ease-in-out infinite;
			}

			&.circle2 {
				width: 150rpx;
				height: 150rpx;
				top: 50rpx;
				left: -75rpx;
				animation: float 8s ease-in-out infinite reverse;
			}

			&.circle3 {
				width: 100rpx;
				height: 100rpx;
				top: 150rpx;
				right: 100rpx;
				animation: float 10s ease-in-out infinite;
			}
		}
	}

	@keyframes float {

		0%,
		100% {
			transform: translateY(0px);
		}

		50% {
			transform: translateY(-20px);
		}
	}

	// 头部区域
	.header-section {
		text-align: center;
		margin-top: 100rpx;
		margin-bottom: 80rpx;
		z-index: 1;

		.logo-container {
			margin-bottom: 40rpx;

			.logo {
				width: 120rpx;
				height: 120rpx;
				border-radius: 24rpx;
				box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
			}
		}

		.app-title {
			font-size: 56rpx;
			font-weight: bold;
			color: #333;
			display: block;
			margin-bottom: 16rpx;
		}

		.welcome-text {
			font-size: 28rpx;
			color: #666;
			display: block;
		}
	}

	// 登录卡片
	.login-card {
		background: #fff;
		border-radius: 32rpx;
		padding: 60rpx 40rpx;
		margin-bottom: 60rpx;
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
		z-index: 1;

		.card-header {
			text-align: center;
			margin-bottom: 60rpx;

			.card-title {
				font-size: 44rpx;
				font-weight: bold;
				color: #333;
				display: block;
				margin-bottom: 16rpx;
			}

			.card-subtitle {
				font-size: 28rpx;
				color: #666;
				display: block;
			}
		}

		// 按钮区域
		.button-section {
			.wx-login-btn {
				width: 100%;
				height: 96rpx;
				background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
				color: #fff;
				border: none;
				border-radius: 48rpx;
				font-size: 32rpx;
				font-weight: bold;
				margin-bottom: 24rpx;
				box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);
				transition: all 0.3s ease;

				&:active {
					transform: translateY(2rpx);
					box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
				}

				&:disabled {
					background: #ccc;
					box-shadow: none;
					transform: none;
				}

				.btn-content {
					display: flex;
					align-items: center;
					justify-content: center;

					.wx-icon {
						font-size: 36rpx;
						margin-right: 16rpx;
					}

					.btn-text {
						font-size: 32rpx;
					}
				}
			}
		}

		// 状态区域
		.status-section {
			margin-top: 32rpx;

			.status-message {
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 24rpx;
				border-radius: 16rpx;
				margin-bottom: 16rpx;

				&.success {
					background: #d4edda;
					border: 2rpx solid #c3e6cb;
					color: #155724;
				}

				&.error {
					background: #f8d7da;
					border: 2rpx solid #f5c6cb;
					color: #721c24;
				}

				&.info {
					background: #d1ecf1;
					border: 2rpx solid #bee5eb;
					color: #0c5460;
				}

				.status-icon {
					font-size: 32rpx;
					margin-right: 16rpx;
				}

				.status-text {
					font-size: 28rpx;
					line-height: 1.4;
				}
			}
		}
	}

	// 功能说明
	.feature-section {
		display: flex;
		justify-content: space-around;
		margin-bottom: 60rpx;
		z-index: 1;

		.feature-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 24rpx;

			.feature-icon {
				font-size: 48rpx;
				margin-bottom: 16rpx;
			}

			.feature-text {
				font-size: 24rpx;
				color: #666;
				text-align: center;
			}
		}
	}

	// 底部协议
	.agreement-section {
		margin-top: auto;
		padding-top: 40rpx;
		z-index: 1;
		display: flex;
		justify-content: center;
		align-items: center;

		.agreement-wrapper {
			width: 100%;
			display: flex;
			justify-content: center;

			.agreement-text {
				font-size: 24rpx;
				color: #999;
				text-align: center;
				line-height: 1.6;

				.agreement-link {
					color: #667eea;
					text-decoration: underline;
				}
			}
		}
	}
</style>